<template>
  <!-- :immediate-check="false" -->
  <van-list v-model:loading="listPage.listLoading" :finished="listPage.listFinished" finished-text="没有更多了"
    @load="onListLoad">
    <!-- 插槽传递 listArr 数据 -->
    <slot :list="listArr"></slot>
  </van-list>
</template>

<script setup>

/** 一个长列表，用于分页的组件 */

import { ref, reactive, onMounted, watch } from 'vue'

const props = defineProps({
  action: {
    type: Function,
    required: true
  },
  queryParams: {
    type: Object,
    default: {}
  },
  pageSize: {
    type: Number,
    default: 5
  }
})

const reset = () => {
  listArr.value = [];
  listPage.value.pageNum = 1;
  listPage.value.listFinished = false;
}

const refresh = async () => {
  reset();

  await onListLoad(); // 主动加载第一页数据
}

defineExpose({ reset, refresh });

const listArr = ref([]);

const listPage = ref({
  pageNum: 1,
  pageSize: props.pageSize,
  listLoading: false,
  listFinished: false,
});

// 加载数据
const onListLoad = async () => {
  try {
    listPage.value.listLoading = true

    const response = await props.action({
      ...(props.queryParams),
      pageNum: listPage.value.pageNum,
      pageSize: listPage.value.pageSize
    })

    // 更新列表数据
    listArr.value = [...listArr.value, ...response.records]

    // 判断是否还有下一页
    if (listPage.value.pageNum * listPage.value.pageSize < response.total) {
      listPage.value.pageNum += 1
    } else {
      listPage.value.listFinished = true
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    listPage.value.listFinished = true
  } finally {
    listPage.value.listLoading = false
  }
}

// 监听 queryParams 变化并重置分页 & 数据
watch(
  () => props.queryParams,
  (newVal, oldVal) => {
    if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
      listArr.value = []
      listPage.value.pageNum = 1
      listPage.value.listFinished = false
      listPage.value.listLoading = false

      // 立即请求新数据
      onListLoad()
    }
  },
  {
    "immediate-check": false,
    deep: true
  }
)
</script>

<style lang="scss" scoped></style>